# -*- coding: utf-8 -*-
# &&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&
# AmosERP odoo11.0
# QQ:35350428
# 邮件:35350428@qq.com
# 手机：13584935775
# 作者：'odoo'
# 公司网址： www.odoo.pw  www.100china.cn www.amoserp.com
# Copyright 昆山一百计算机有限公司 2012-2020 Amos
# 日期：2019/11/14
# &&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&
from odoo import api, fields, models, SUPERUSER_ID, tools, _
from odoo.exceptions import AccessError, UserError, ValidationError
from ding_client import Client


class Res_Chat_Message(models.Model):
    _name = 'res.chat.message'
    _description = u"向群发送text消息体格式"
    _order = 'id desc'  # ASC

    def _default_company_id(self):
        # return self.env['res.company'].browse(self._context.get('company_id'))
        return self._context.get('company_id')

    def _default_chatid_id(self):
        return self._context.get('active_id')

    def _default_type(self):
        return self._context.get('type')

    name = fields.Char(string=u'发件人', default=lambda self: self.env.user.name)
    company_id = fields.Many2one('res.company', string=u'公司', default=_default_company_id)
    message = fields.Text(string=u'消息')
    chatid_id = fields.Many2one('res.chat', string=u'群', default=_default_chatid_id)
    file = fields.Binary(string=u'附件', )

    @api.model
    def _get_type(self):
        parm = [
            ('text', u'text消息'),
            ('image', u'image消息'),
            ('voice', u'voice消息'),
            ('file', u'file消息'),
            ('link', u'link消息体格式'),
            ('oa', u'OA消息'),
        ]
        return parm

    type = fields.Selection('_get_type', string=u'类型', default=_default_type,
                            readonly=True, )

    def but_yes(self):
        self._cr.execute("SELECT access_token FROM res_ding WHERE company_id = %s " % int(self._context['company_id']))
        access_token = [r[0] for r in self._cr.fetchall()]

        if len(access_token) == 0:
            pass
            #:::执行生成token
        else:
            client_obj = Client(None, None, access_token[0])

            users = self.env['res.users'].browse(self._context['owner'])
            parm = {
                'chatid': self._context['chatid'],
                'sender': users.ding_userid,
                'msgtype': "text",
                'text': {
                    "content": self._context['message']
                },
            }
            json = client_obj.chat_send(parm, access_token[0])


            if json['errcode'] == 40014:
                records = self.env['res.ding'].search([('company_id', '=', int(self._context['company_id']))], limit=1)
                records.action_gettoken()
                self.but_yes();
            else:
                if json['errcode'] != 0:
                    raise ValidationError(json['errmsg'])

class Res_Chat(models.Model):
    _name = 'res.chat'
    _description = u"群"

    name = fields.Char(string=u'群名称', help=u'长度限制为1~20个字符')
    chatid = fields.Char(string=u'群id')
    company_id = fields.Many2one('res.company', string=u'公司', default=lambda self: self.env.user.company_id)
    owner = fields.Many2one('res.users', string=u'群主', help=u'群主userId，员工唯一标识ID；必须为该会话useridlist的成员之一')
    useridlist = fields.Many2many('res.users', 'ding_chat_users_rel', 'chat_id', 'user_id', string=u"群成员",
                                  help=u'每次最多操作40人，群人数上限为1000')

    message_ids = fields.One2many('res.chat.message', 'chatid_id', string=u"文本消息")

    @api.model
    def create(self, values):
        line = super(Res_Chat, self).create(values)

        self._cr.execute("SELECT access_token FROM res_ding WHERE company_id = %s " % values['company_id'])
        access_token = [r[0] for r in self._cr.fetchall()]

        if len(access_token) == 0:
            pass
            #:::执行生成token
        else:
            client_obj = Client(None, None, access_token[0])
            useridlist = []
            for user in line.useridlist:
                useridlist.append(user.ding_userid)
            params = {
                "name": line.name,
                "owner": line.owner.ding_userid,
                "useridlist": list(useridlist),
            }
            json = client_obj.chat_create(params, access_token[0])

            if json['errcode'] == 40014:
                records = self.env['res.ding'].search([('company_id', '=', values['company_id'])], limit=1)
                records.action_gettoken()
                self.create();
            else:
                if json['errcode'] != 0:
                    raise ValidationError(json['errmsg'])

            parm = {
                'chatid': json['chatid'],
            }
            line.with_context(bing_sync=True).write(parm)
        return line

    def write(self, values):
        result = super(Res_Chat, self).write(values)
        if self._context.has_key('bing_sync'):
            pass
        else:
            self._cr.execute("SELECT access_token FROM res_ding WHERE company_id = %s " % self.company_id.id)
            access_token = [r[0] for r in self._cr.fetchall()]
            if len(access_token) == 0:
                pass
                #:::执行生成token
            else:
                client_obj = Client(None, None, access_token[0])
                useridlist = []
                for user in self.useridlist:
                    useridlist.append(user.ding_userid)
                parm = {
                    'chatid': self.chatid,
                    'name': self.name,
                    "owner": self.owner.ding_userid,
                    "useridlist": list(useridlist),
                }
                json = client_obj.chat_update(parm, access_token[0])


                if json['errcode'] == 40014:
                    records = self.env['res.ding'].search([('company_id', '=', self.company_id.id)], limit=1)
                    records.action_gettoken()
                    self.write();
                else:
                    if json['errcode'] != 0:
                        raise ValidationError(json['errmsg'])

        return result

    def action_chat_send(self):
        """
        发送消息到群会话
        """
        for line in self:
            self._cr.execute("SELECT access_token FROM res_ding WHERE company_id = %s " % line.company_id.id)
            access_token = [r[0] for r in self._cr.fetchall()]

            if len(access_token) == 0:
                pass
                #:::执行生成token
            else:
                client_obj = Client(None, None, access_token[0])
                parm = {
                    'chatid': line.chatid,
                    'sender': line.owner.ding_userid,
                    'msgtype': "text",
                    'text': {
                        "content": "Amos群消息发送测试"
                    },
                }
                json = client_obj.chat_send(parm, access_token[0])

                if json['errcode'] == 40014:
                    records = self.env['res.ding'].search([('company_id', '=', line.company_id.id)], limit=1)
                    records.action_gettoken()
                    self.action_chat_send();
                else:
                    if json['errcode'] != 0:
                        raise ValidationError(json['errmsg'])

